package com.geek;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

public class DownLoadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取要下载文件的路径
        String srcPath = "E:\\studynom\\mavenMain\\01-servlet\\target\\classes\\file\\a.html";
        System.out.println("源文件路径:" + srcPath);

        //获取下载的文件名(还能获取文件类型，超级好用)
        String fileName = srcPath.substring(srcPath.lastIndexOf("\\") + 1);
        //获取下载文件的类型，自动判断文件类型
        resp.setContentType("multipart/form-data");
        //设置使浏览器支持下载文件的头信息
        resp.setHeader("Content-disposition", "attachment;filename=" + fileName);
        //获取下载文件的输入流
        FileInputStream fin = new FileInputStream(srcPath);
        //创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        //获取outputStream对象
        ServletOutputStream outputStream = resp.getOutputStream();
        //将FileInputStream流写入buffer缓冲区，使用outputStream将缓冲区中的数据输出到客户端
        while ((len = fin.read(buffer)) > 0) {
            outputStream.write(buffer, 0, len);
        }
       //-----------------
     /*   while ((len=is.read(buffer))>0){
            outputStream.write(buffer,0,len);
        }*/
        //------------------

        fin.close();
        outputStream.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
